<template>
	<view class="Global">
		<!-- <image class="imagepage" src="/static/background@2x.png" mode=""></image> -->
		<bgImage></bgImage>
		<MyNav :title="title" bgColor="" :backIcon="isback"></MyNav>



		<scroll-view scroll-y="true" class="contentCenter"  :style="'height:'+scrollViewHeight+'px'">
			<view class="Content">

<!-- 未连接的状态图 -->
				 <image src="/static/gongzuotai/zanwushebei.png" v-if="BLEInformation.deviceId==''" class="shebeiContent" mode=""></image>
			<!--  已连接状态图 -->
				<image src="/static/gongzuotai/yilianjie.png" v-else class="shebeiContentOnline" mode=""></image>

				<text class="tipsContent" v-if="BLEInformation.deviceId==''||BLEInformation.deviceId==undefined">暂无已配对设备，点击蓝牙搜索设备</text>
				<text class="tipsContent" v-else>已连接设备：{{BLEInformation.name}}</text>

				<view class="faxianContent">
					<text class="faxianContentText">发现可连接设备</text>

					<text class="faxianContentTextFresh" @click="startSearch()">刷新</text>
				</view>



				<!-- 设备列表开始 -->
				<view class="shebeiListContent">

					<view class="shebeiListContentInner" v-for="(item,index) in deviceListData">

						<view class="shebeiListContentInnerLeft">
							<image class="shebeiListContentInnerLeftImg" src="/static/gongzuotai/dayinji@2x.png" mode="">
							</image>
							<text class="shebeiListContentInnerLeftText">{{item.name}}</text>
						</view>

						<view class="shebeiListContentInnerRight">
							<text class="shebeiListContentInnerRightText" v-if="BLEInformation.deviceId!==item.deviceId" @click="bindViewTap(item)">连接</text>
							<text class="shebeiListContentInnerRightText" v-else @click="closeBlue">已连接</text>
						</view>

					</view>

				</view>
				<!-- 设备列表结束 -->




				<view class="loginContent">

					<button @click="startSearch()" style="color:#ffffff" class="login" type="default">{{login}}</button>
				</view>




				<view class="bottomBtnContent">

					<text class="bottomBtnContentText" @click="openControl()">打印测试</text>
					<text class="bottomBtnContentText" @click="queryStatus">状态检测</text>

				</view>


			</view>
		</scroll-view>


	</view>
</template>

<script>
	import MyNav from '@/components/customnavbar.vue'
import bgImage from '@/components/backgroundImage.vue'
  import tsc from "../../../components/utils/tsc";

	export default {
		components: {
			MyNav,
			bgImage
		},
		data() {
			return {
				login: '蓝牙搜索',

				title: '设置打印机',
				isback: true,


				// 设备列表

				deviceListData: [],

				scrollViewHeight:0,

        data: {
          looptime: 0,
          currentTime: 1,
          lastData: 0,
          oneTimeData: 0,
          buffSize: [],
          buffIndex: 0, //发送字节数下标
          printNum: [],
          printNumIndex: 0,
          printerNum: 1,
          currentPrint: 1,
          isLabelSend: false,
          isQuery: false,
          imageSrc: '/static/logo.png',
          jpgSrc: '/static/logo.png',
          canvasWidth: 100,
          canvasHeight: 100,
          jpgWidth: 200,
          jpgHeight: 200,
        },

        services: [],
        serviceId: 0,
        writeCharacter: false,
        readCharacter: false,
        notifyCharacter: false,
        isScanning: false,
        BLEInformation: {
          platform: "",
          deviceId: "",
          name: "",
          writeCharaterId: "",
          writeServiceId: "",
          notifyCharaterId: "",
          notifyServiceId: "",
          readCharaterId: "",
          readServiceId: "",
        }


			}
		},
    onShow(){
      this.startSearch()
    },
		onLoad() {
			// 在其他页面或组件中访问
			const app = getApp();
			this.scrollViewHeight=app.globalData.scrollViewHeight2

      this.BLEInformation = uni.getStorageSync('bluetooth')
      if(this.BLEInformation.deviceId!=''){
        this.bindViewTap(this.BLEInformation)
      }
		},
		methods: {
      closeBlue(){
        let that = this
        uni.closeBLEConnection({
          deviceId: that.BLEInformation.deviceId,
          success(res) {
            console.log(res)
            that.BLEInformation.deviceId = ''
            that.BLEInformation.name = ''
            uni.setStorageSync('bluetooth',that.BLEInformation)
            uni.showToast({
              title: '已断开蓝牙连接'
            });
          }
        });
      },
      //搜索设备
      startSearch() {
        this.list=[]
        var that = this
        uni.openBluetoothAdapter({
          success(res) {
            uni.getBluetoothAdapterState({
              success:(res) =>{
                console.log('openBluetoothAdapter success', res)
                uni.showToast({
                  title: '刷新'
                });
                if (res.available) {
                  if (res.discovering) {
                    uni.stopBluetoothDevicesDiscovery({
                      success(res) {
                        console.log(res)
                      }
                    })
                  } else {
                    // that.startBluetoothDevicesDiscovery()
                    that.getBluetoothDevices()
                  }
                  // that.checkPemission()
                } else {
                  uni.showModal({
                    title: '提示',
                    content: '本机蓝牙不可用',
                    showCancel: false
                  })
                }
              },
              fail: (res) => {
                uni.showToast({
                  title: '调用失败'
                });
              }
            })
          },
          fail() {
            uni.showModal({
              title: '提示',
              content: '蓝牙初始化失败，请到设置打开蓝牙',
              showCancel: false
            })
          }
        })
      },
      getBluetoothDevices() { //获取蓝牙设备信息
        var that = this
        console.log("start search")
        uni.showLoading({
          title: '正在加载中',
          icon: 'loading',
        })
        that.isScanning=true
        uni.startBluetoothDevicesDiscovery({
          success:(res)=> {
            // console.log(res)

            setTimeout(function() {
              that.getBluetoothDevicesData()
            }, 5000)
          },
          fail: () => {
            uni.showToast({
              title: '调用失败11'
            });
          }
        })
      },

      getBluetoothDevicesData(){
        var that = this
        uni.getBluetoothDevices({
          success:(res)=>  {
            console.log('getBluetoothDevices',res)
            that.deviceListData=[...that.deviceListData,...res.devices]
            // 使用filter和findIndex进行去重
            let uniqueDataList = that.deviceListData.filter((item, index, self) => {
              // 返回第一个匹配项的索引，用于判断当前项是否为第一个匹配项
              const firstIndex = self.findIndex((obj) => obj.deviceId === item.deviceId);

              // 如果当前项是第一个匹配项，则保留，否则过滤掉
              return index === firstIndex;
            });
            that.deviceListData = uniqueDataList.filter(item=>{
              if(item.name!=='未知设备'){
                return item;
              }
            });

            uni.hideLoading()
            uni.stopPullDownRefresh()
            uni.stopBluetoothDevicesDiscovery({
              success(res) {
                console.log("停止搜索蓝牙")
              }
            })
          },
          fail: (res) => {
            uni.showToast({
              title: '调用失败'
            });
          },
          complete: () => {
            /* uni.showToast({
              title:'完成调用'
            }) */
          }
        })
      },
      bindViewTap(e) {
        var that = this
        uni.stopBluetoothDevicesDiscovery({
          success(res) {
            console.log(res)
          },
        })
        that.serviceId=0
        that.writeCharacter=false
        that.readCharacter=false
        that.notifyCharacter=false

        // console.log(e.currentTarget.dataset.title)
        uni.showLoading({
          title: '正在连接',

        })
        uni.createBLEConnection({
          deviceId: e.deviceId,
          success(res) {
            console.log(res)
            that.BLEInformation.deviceId=e.deviceId
            that.BLEInformation.name=e.name
            that.getSeviceId(e.deviceId)

          },
          fail(e) {
            uni.showModal({
              title: '提示',
              content: '连接失败',
              showCancel: false
            })
            console.log(e)
            uni.hideLoading()
          },
          complete(e) {
            console.log(e)
          }
        })
      },
      getSeviceId(e) {
        var that = this
        uni.getBLEDeviceServices({
          deviceId: e,
          success(res) {
            console.log(res)
            that.getCharacteristics(res.services)
          },
          fail(e) {
            console.log(e)
            uni.showModal({
              title: '调用失败1',
              content: JSON.stringify(e),
              showCancel: false,
              cancelText: '',
              confirmText: '确认',
              success: res => {},
              fail: () => {},
              complete: () => {}
            });
          },
          complete(e) {
            console.log(e)
          }
        })
      },
      getCharacteristics(e) {
        var that = this
        var list = e
        var num = that.serviceId
        var write = that.writeCharacter
        var read = that.readCharacter
        var notify = that.notifyCharacter


        uni.getBLEDeviceCharacteristics({
          deviceId: that.BLEInformation.deviceId,
          serviceId: list[num].uuid,
          success(res) {
            console.log(res)
            /* uni.showModal({
              title: '',
              content: JSON.stringify(res),
              showCancel: false,
              cancelText: '',
              confirmText: 'chara',
              success: res => {},
              fail: () => {},
              complete: () => {}
            }); */

            for (var i = 0; i < res.characteristics.length; ++i) {
              var properties = res.characteristics[i].properties
              var item = res.characteristics[i].uuid
              if (!notify) {
                if (properties.notify) {
                  that.BLEInformation.notifyCharaterId = item
                  that.BLEInformation.notifyServiceId = list[num].uuid
                  notify = true
                }
              }
              if (!write) {
                if (properties.write) {
                  that.BLEInformation.writeCharaterId = item
                  that.BLEInformation.writeServiceId = list[num].uuid
                  write = true
                }
              }
              if (!read) {
                if (properties.read) {
                  that.BLEInformation.readCharaterId = item
                  that.BLEInformation.readServiceId = list[num].uuid
                  read = true
                }
              }
            }
            if (!write || !notify || !read) {
              num++
              that.setData({
                writeCharacter: write,
                readCharacter: read,
                notifyCharacter: notify,
                serviceId: num
              })
              if (num == list.length) {
                uni.showModal({
                  title: '提示',
                  content: '找不到该读写的特征值',
                  showCancel: false
                })
              } else {
                that.getCharacteristics(e)
              }
            } else {
              uni.showToast({
                title: '连接成功',
              })
              // that.openControl()
              uni.setStorageSync("bluetooth", that.BLEInformation)
              console.log('bluetooth',uni.getStorageSync('bluetooth'))
            }
          },
          fail(e) {
            console.log(e)
            uni.showModal({
              title: '连接失败',
              content: JSON.stringify(e),
              showCancel: false,
              cancelText: '',
              confirmText: '确认',
              success: res => {},
              fail: () => {},
              complete: () => {}
            });
          },
          complete(e) {
            console.log("write:" + that.BLEInformation.writeCharaterId)
            console.log("read:" + that.BLEInformation.readCharaterId)
            console.log("notify:" + that.BLEInformation.notifyCharaterId)
          }
        })
      },
      openControl() {
        //连接成功返回主页
        if(this.BLEInformation.deviceId==''){
          uni.showToast({
            title: '暂无已配对设备',
            icon: 'none',
          })
          return false
        }
        uni.navigateTo({
          url: '/subPack/bluetooth/printLabel/printLabel?item=' +
              encodeURIComponent(JSON.stringify(this.BLEInformation)),
        })

      },
      queryStatus: function() {
        //查询打印机状态
        if(this.BLEInformation.deviceId==''){
          uni.showToast({
            title: '暂无已配对设备',
            icon: 'none',
          })
        }
        var that = this
        var buf;
        var dateView;
        /*
        n = 1：传送打印机状态
        n = 2：传送脱机状态
        n = 3：传送错误状态
        n = 4：传送纸传感器状态
        */
        buf = new ArrayBuffer(5)
        dateView = new DataView(buf)
        dateView.setUint8(0, 27)
        dateView.setUint8(1, 33)
        dateView.setUint8(2, 63)
        dateView.setUint8(3, 13)
        dateView.setUint8(4, 10)
        uni.writeBLECharacteristicValue({
          deviceId: that.BLEInformation.deviceId,
          serviceId: that.BLEInformation.writeServiceId,
          characteristicId: that.BLEInformation.writeCharaterId,
          value: buf,
          success: function(res) {
            console.log("发送成功")

            that.data.isQuery = true
          },
          fail: function(e) {
            uni.showToast({
              title: '发送失败',
              icon: 'none',
            })
            //console.log(e)
            return;
          },
          complete: function() {

          }
        })

        uni.notifyBLECharacteristicValueChange({
          deviceId: that.BLEInformation.deviceId,
          serviceId: that.BLEInformation.notifyServiceId,
          characteristicId: that.BLEInformation.notifyCharaterId,
          state: true,
          success: function(res) {
            uni.onBLECharacteristicValueChange(function(r) {
              console.log(
                  `characteristic ${r.characteristicId} has changed, now is ${r}`
              )
              var result = that.ab2hex(r.value)
              console.log("返回" + result)
              var tip = ''
              if (result == 0) { //正常
                tip = "正常"
              } else if (result == 4) { //缺纸
                tip = "缺纸"
              } else if (result == 5) { //开盖、缺纸
                tip = "开盖、缺纸"
              } else if (result == 41) {
                tip = "开盖"
              } else if (result == 40) { //其他错误
                tip = "其他错误"
              } else { //未处理错误
                tip = "未知错误"
              }
              uni.showModal({
                title: '打印机状态',
                content: tip,
                showCancel: false
              })

            })
          },
          fail: function(e) {
            uni.showModal({
              title: '打印机状态',
              content: '获取失败',
              showCancel: false
            })
            console.log(e)
          },
          complete: function(e) {

            that.data.isQuery = false
            console.log("执行完成")
          }
        })
      },
      // ArrayBuffer转16进度字符串示例
      ab2hex(buffer) {
        var hexArr = Array.prototype.map.call(
            new Uint8Array(buffer),
            function(bit) {
              return ('00' + bit.toString(16)).slice(-2)
            }
        )
        return hexArr.join('');
      },
		},
	}
</script>

<style>

	.contentCenter{
		display: flex;
		justify-content: center;
		align-items: center;
		flex-direction: column;

		width: 100%;
		height: 1100rpx;
	}
	.Content{
		display: flex;
		justify-content: center;
		align-items: center;
		flex-direction: column;
	}

	.imagepage {

		background-size: cover;
		background-repeat: no-repeat;
		background-position: center center;
		position: absolute;
		z-index: -1;
		left: 0;
		right: 0;
		bottom: 0;
		right: 0;
		width: 100%;
		height: 100%;

	}

	.bottomBtnContentText {
		display: flex;
		justify-content: center;
		align-items: center;

		width: 210rpx;
		height: 100rpx;
		background: #FFFFFF;

		border-radius: 20rpx;


		font-family: HarmonyOS Sans SC;
		font-weight: 400;
		font-size: 28rpx;
		color: #0081FF;
		line-height: 30rpx;

	}

	.bottomBtnContent {

		display: flex;
		justify-content: space-evenly;
		align-items: center;
		width: 100%;
		margin-top: 30rpx;
		margin-bottom: 30rpx;
	}


	.loginContent {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		width: 750rpx;


	}

	.login {
		display: flex;
		justify-content: center;
		margin-top: 40rpx;
		align-items: center;
		text-align: center;


		font-family: HarmonyOS Sans SC;
		font-weight: 400;
		font-size: 28rpx;
		color: #FFFFFF;
		line-height: 30rpx;

		width: 690rpx;
		height: 100rpx;
		background: linear-gradient(90deg, #45A8FF, #0AE1C6);
		border-radius: 20rpx;




	}


	.shebeiListContentInnerLeftText {

		font-family: HarmonyOS Sans SC;
		font-weight: 400;
		font-size: 28rpx;
		color: #333333;
		line-height: 30rpx;


	}

	.shebeiListContentInnerRightText {

		width: 140rpx;
		height: 60rpx;
		background: #FFFFFF;
		border-radius: 16rpx;

		display: flex;
		justify-content: center;
		align-items: center;

		font-family: HarmonyOS Sans SC;
		font-weight: 400;
		font-size: 24rpx;
		color: #0081FF;
		line-height: 36rpx;

		margin-right: 30rpx;
	}

	.shebeiListContentInnerRight {

		display: flex;
		justify-content: center;
		align-items: center;
	}


	.shebeiListContentInnerLeftImg {

		width: 30rpx;
		height: 30rpx;
		margin-left: 30rpx;
		margin-right: 30rpx;
	}


	.shebeiListContentInnerLeft {
		display: flex;
		justify-content: center;
		align-items: center;
		flex-direction: row;
	}


	.shebeiListContentInner {

		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;

		width: 100%;
		margin-bottom: 70rpx;
	}



	.shebeiListContent {
		display: flex;
		justify-content: center;
		align-items: center;
		flex-direction: column;

		width: 100%;

		margin-top: 70rpx;
	}






	.faxianContentTextFresh {


		font-family: HarmonyOS Sans SC;
		font-weight: 400;
		font-size: 24rpx;
		color: #FFFFFF;
		line-height: 30rpx;

		display: flex;
		justify-content: center;
		align-items: center;
		margin-right: 30rpx;

		width: 100rpx;
		height: 50rpx;
		background: linear-gradient(90deg, #45A8FF, #0AE1C6);
		border-radius: 16rpx;
	}

	.faxianContentText {
		width: 250rpx;
		height: 35rpx;
		font-family: HarmonyOS Sans SC;
		font-weight: bold;
		font-size: 36rpx;
		color: #333333;
		line-height: 30rpx;

		display: flex;
		justify-content: center;
		align-items: center;
		margin-left: 30rpx;
	}

	.faxianContent {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-top: 110rpx;
		width: 100%;
	}

	.tipsContent {
		display: flex;
		justify-content: center;
		align-items: center;

		margin-top: 30rpx;
		width: 446rpx;
		height: 29rpx;
		font-family: HarmonyOS Sans SC;
		font-weight: 400;
		font-size: 28rpx;
		color: #999999;
		line-height: 30rpx;


	}

	.shebeiContent {
		display: flex;
		justify-content: center;
		align-items: center;

		width: 430rpx;
		height: 229rpx;

		margin-top: 120rpx;
	}
	.shebeiContentOnline{
		display: flex;
		justify-content: center;
		align-items: center;

		width: 269rpx;
		height: 258rpx;

		margin-top: 120rpx;
	}
</style>
